package com.zhengke.controller.coolxinController;

/**
 * *******************************
 * 项目名称：tvmallws
 * 文件名称：JfdhController
 * 类说明：  积分兑换
 * 创建时间：2020/1/13 11:44
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
import com.zhengke.common.BaseController;
import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.Result;
import com.zhengke.common.object.ZTreeNode;
import com.zhengke.pojo.*;
import com.zhengke.service.coolxinService.JfdhService;
import com.zhengke.service.directory.SysDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("XD020")
public class JfdhController extends BaseController {

    @Autowired
    private JfdhService service;

    @Autowired
    private SysDictionaryService sysDictionaryService;
    /**
     * 到积分兑换-服务点列表页面
     * @return
     */
    @RequestMapping("jfdhMsg.do")
    public String query(){
        return "coolxinPages/xzxd/jfdh010";
    }

    /**
     * 服务点列表树
     * @param id
     * 返回数据字典的Json格式数据
     */
    @ResponseBody
    @RequestMapping("tree.do")
    public List<ZTreeNode> tree(String id) throws Exception {
        //System.out.println(id);
        List<ZTreeNode> list = new ArrayList<ZTreeNode>();
        if (id != null)
        {
            list = service.queryParent(id);
            return list;
        }
        list = service.queryParent("0");
        return list ;
    }

    /**
     * @return
     * 到服务点积分兑换商品页面
     */
    @RequestMapping("toMsg.do")
    public String toMsg(String areaId, ModelMap model)  {
        //System.out.println(areaId);
        model.put("areaId",areaId);
        return "coolxinPages/xzxd/jfdh0102";
    }

    /**
     * 服务点积分兑换商品详情
     * @param areaId
     * @param goodsName
     * @param property
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("toQueryMsg.do")
    public Result toQueryMsg(String areaId, String goodsName, String property, HttpServletRequest request,int page, int limit) {
        Result rs = null;
        try {
            rs = service.queryMsg(areaId, goodsName, property,page,limit);
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }

    /**
     * 查询会员
     */
    @ResponseBody
    @RequestMapping("toQueryUser.do")
    public AjaxDone toQueryUser(HttpServletRequest request){
        String userCardNumber = request.getParameter("userCardNumber");
        try {
            List<TvUser> rst = service.queryUser(userCardNumber);
            if(null == rst || rst.size() ==0 ){
                return new AjaxDone("300", "查无此人，请重新输入！","","");
            }else{
                return new AjaxDone("200", "查询成功，请核实！","",rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 跳转下单详情页
     */
    @RequestMapping("toBuyPage.do")
    public String toBuyPage() {
        return "coolxinPages/xzxd/toBuy";
    }

    /**
     * 加载下单商品详情
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("toBuyDetail.do")
    @ResponseBody
    public AjaxDone toBuyDetail(HttpServletRequest request) throws Exception {
        String goodsId = request.getParameter("goodsId");
        //System.out.println("goodsId----->"+goodsId);
        List<ToBuyMsg> rtnList = service.queryToBuyMsg(goodsId);
        if(null == rtnList || rtnList.size() ==0 ){
            return new AjaxDone("300", "数据异常，请重新操作！","","");
        }else{
            return new AjaxDone("200", "查询成功！","",rtnList);
        }
    }

    /**
     * 确定下单
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("toBuy.do")
    @ResponseBody
    public AjaxDone toBuy(HttpServletRequest request) throws Exception {
        String userCardNumber = request.getParameter("tvUserMsg[userCardNumber]");
        Integer servicePointId = Integer.parseInt(request.getParameter("tvUserMsg[servicePointId]"));//服务点id
        TvUser user = service.queryTvUser(userCardNumber);

        String goodsId = request.getParameter("toBuyGoodsMsg[goodsId]");
        //预定限额
        String goodsDestineQuota = request.getParameter("toBuyGoodsMsg[goodsDestineQuota]");
        //库存
        String goodsStorage = request.getParameter("toBuyGoodsMsg[goodsStorage]");
        //商品单价
        BigDecimal goodsPrice = new BigDecimal(request.getParameter("toBuyGoodsMsg[goodsPrice]"));
        ToBuyMsg toBuyMsgObj = service.queryToBuyMsgObj(goodsId);

        //购买数量
        String number = request.getParameter("data[number]");
        //邮费（积分）
        String shippingFeeExch = request.getParameter("data[shippingFeeExch]");
        //邮费（￥）
        String shippingFee = request.getParameter("data[shippingFee]");
        //配送方式 0 配送 1 自取
        String getWaySelect = request.getParameter("data[getWaySelect]");
        //赠送积分
        BigDecimal sendInte = new BigDecimal(request.getParameter("data[sendInte]"));
        //共需积分
        BigDecimal exchIntegralAmount = new BigDecimal(request.getParameter("data[exchIntegralAmount]"));

        //当前日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String updateTime = df.format(new Date());// new Date()获取当前系统时间
        try {
            /**
             *构造保存订单信息
             */
            TvOrder to = new TvOrder();
            to.setOrderSn(user.getUserId()+String.format("%013d",(new Date().getTime())));//订单编号
            to.setUserId(user.getUserId()); //用户id tvn号码
            to.setUserName(user.getUserName()); //用户名称
            to.setUserCardNumber(user.getUserCardNumber()); //用户卡号
            to.setAddTime(updateTime);//生成时间
            to.setServicePointId(servicePointId);//服务点id
            to.setReceiverName(user.getUserName());
            to.setReceiverAddress(user.getAddressDetail());
            to.setReceiverPhone(user.getUserPhone());
            to.setReceiveProvinceId(user.getProvinceId());
            to.setReceiveCityId(user.getCityId());
            to.setReceiptMethod(Short.parseShort(getWaySelect));//收货方式(0：上门送，1：自取)
            to.setOrderState((short)10);//订单状态：0:已取消;10(默认):待确认;20:已确认;30:已配货;40:已发货;50:已收款;60:已退货
            to.setIntegralHandsel(sendInte);//赠送积分

            /**
             *构造保存订单商品信息
             */
            TvOrderGoods tog = new TvOrderGoods();
            tog.setGoodsName(toBuyMsgObj.getGoodsName());
            tog.setGoodsTime(updateTime);
            tog.setSpecifications(toBuyMsgObj.getSpecifications());
            tog.setGoodsNum(new BigDecimal(number));
            tog.setServicePointId(servicePointId);
            tog.setUserId(user.getUserId());
            tog.setState((short)1);//状态(0：取消，1：确认,2:退货)
            to.setIsExperie((short)2);//订单类型(0：普通商品,1：体验品,2:积分兑换商品)
            /*
            判断是否可以兑换成功
             */
            //设置总价（￥）
            BigDecimal amountPrice = goodsPrice.multiply(new BigDecimal(number));
            if (getWaySelect.equals("0")){ //配送 ，加运费
                amountPrice = amountPrice.add(new BigDecimal(shippingFee));
                to.setGoodsAmount(amountPrice);//商品总价格
                to.setOrderAmount(amountPrice);//订单总价格
            }else {
                to.setGoodsAmount(amountPrice);//商品总价格
                to.setOrderAmount(amountPrice);//订单总价格
            }
            /*
                bigdemical比较大小用compareTo
                flag = -1,表示bigdemical1小于bigdemical2
                flag = 0,表示bigdemical1等于bigdemical2；
                flag = 1,表示bigdemical1大于bigdemical2；
             */
            int flag = (user.getUserIntegral()).compareTo(exchIntegralAmount);
            if(flag == -1){
                return new AjaxDone("300","下单失败，用户积分不足");
            }
            tog.setGoodsPrice(goodsPrice);
            tog.setGoodsType(toBuyMsgObj.getIsNormal());
            tog.setGoodsId(Integer.parseInt(goodsId));

            MallServiceGoods01 msg = new MallServiceGoods01();
            msg.setServicePointId(servicePointId);
            msg.setGoodsId(Integer.parseInt(goodsId));
            msg.setGoodsDestineQuota(Integer.parseInt(goodsDestineQuota)-Integer.parseInt(number));//设置预定限额
            msg.setGoodsStorage(new BigDecimal(Integer.parseInt(goodsStorage)-Integer.parseInt(number)));//设置库存

            //下单成功的话，因为是积分兑换，所以只扣除会员积分,加上赠送积分
            //两个BigDecimal类型相减  bignum1.subtract(bignum2)
            user.setUserIntegral((user.getUserIntegral()).subtract(exchIntegralAmount).add(sendInte));
            service.createOrder(to,tog,msg,user);

            return new AjaxDone("200","下单成功！");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new AjaxDone("300","下单失败");
        }
    }
}

